/** @format */

import { resultsModel } from '../../../sdk'
import { CODE_TYPES } from '../../../errorCode'
import { dbFindOne } from '../../common/mongodb'
import { USER_DB_NAME } from '../../../db'
import { getTodayCompleteTask } from '../task'
import { TASK_RATE_TYPE } from '../../../constants'

/**
 *  检查inviteId是否合法 返回邀请人的用户信息
 *
 * @export
 * @param {IContext<{ activityId: string; inviteId: string }>} context
 * @return {*}
 */
export default async function checkInviteId(
  context: IContext<{ activityId: string; inviteId: string }>,
  { activityInfo }: IControllerInfos
) {
  const {
    openId,
    data: { activityId, inviteId }
  } = context

  // 自己邀请自己
  if (openId === inviteId) return resultsModel.error(CODE_TYPES.ERROR_NO_INVITE_SELF)

  // 获取邀请者信息
  const inviteUserInfo = await dbFindOne<IUserInfo>(context, USER_DB_NAME, {
    activityId,
    openId: inviteId
  })

  // inviteId的用户信息查询不到, 则inviteId无效
  if (!inviteUserInfo) return resultsModel.error(CODE_TYPES.ERROR_INVALID_INVITE_ID)

  const {
    tasks: { invite }
  } = activityInfo

  const { rateType, times } = invite
  const { todayCompleteTimes } = getTodayCompleteTask('invite', inviteUserInfo)

  // 助力次数超限制
  if (rateType === TASK_RATE_TYPE.EVERYDAY && todayCompleteTimes >= times) {
    return resultsModel.error(CODE_TYPES.ERROR_INVITE_TIMES_LIMIT)
  }

  return {
    inviteUserInfo
  }
}
